package email.becode.simultaneous_interpretation_android.audio

import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import java.nio.ByteBuffer

class AudioRecordService {
    private var audioRecord: AudioRecord? = null
    private var isRecording = false

        companion object {
            const val SAMPLE_RATE = 16000 // 采样率16kHz
            const val CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_MONO
            const val AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT
            const val BUFFER_SIZE_FACTOR = 2
        }

        fun startRecording(): Flow<ByteArray> = flow {
        val minBufferSize = AudioRecord.getMinBufferSize(
            SAMPLE_RATE,
            CHANNEL_CONFIG,
            AUDIO_FORMAT
        )
        
        val bufferSize = minBufferSize * BUFFER_SIZE_FACTOR
        
        audioRecord = AudioRecord(
            MediaRecorder.AudioSource.MIC,
            SAMPLE_RATE,
            CHANNEL_CONFIG,
            AUDIO_FORMAT,
            bufferSize
        )

        val buffer = ByteBuffer.allocateDirect(bufferSize)
        val audioData = ByteArray(bufferSize)
        
        audioRecord?.startRecording()
        isRecording = true

        while (isRecording) {
            val readSize = audioRecord?.read(buffer, bufferSize) ?: 0
            if (readSize > 0) {
                buffer.get(audioData, 0, readSize)
                emit(audioData.copyOfRange(0, readSize))
                buffer.clear()
            }
        }
    }

    fun stopRecording() {
        isRecording = false
        audioRecord?.stop()
        audioRecord?.release()
        audioRecord = null
    }
} 